package com.zkingsoft.actions.admin;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zkingsoft.actions.common.BaseController;
import com.zkingsoft.anotations.RemoveRequestToken;
import com.zkingsoft.anotations.SaveRequestToken;
import com.zkingsoft.constance.Dictionary;
import com.zkingsoft.dao.UtilDao;
import com.zkingsoft.model.DataDictionary;
import com.zkingsoft.model.ExperienceLevel;
import com.zkingsoft.model.ProjUser;
import com.zkingsoft.model.Project;
import com.zkingsoft.model.Task;
import com.zkingsoft.model.Users;
import com.zkingsoft.plugin.pojo.PaginationVO;
import com.zkingsoft.plugin.util.DateUtils;
import com.zkingsoft.plugin.util.WebUtil;
import com.zkingsoft.pojo.AjaxResult;
import com.zkingsoft.services.DataDictionaryService;
import com.zkingsoft.services.ExperienceLevelService;
import com.zkingsoft.services.ProjUserService;
import com.zkingsoft.services.ProjectService;
import com.zkingsoft.services.TaskService;
import com.zkingsoft.services.UsersService;
import com.zkingsoft.thread.SendOaMsgsThread;

/**
 * This field was generated by Zking.software.Codegen.
 * 
 * @date 2016-11-10 16:57
 */
@Controller
@RequestMapping(value = "admin/task")
public class TaskController extends BaseController {

	@Resource
	private TaskService taskService;
	@Resource
	private DataDictionaryService dataDictionaryService;
	@Resource
	private UsersService usersService;
	@Resource
	private ProjUserService projUserService;
	@Resource
	private ProjectService projectService;
	@Resource
	private ExperienceLevelService exLevelService;
	@Autowired
	private UtilDao utilDao;

	/**
	 * @Description:我接收的任务列表
	 * @author:dingchuan
	 * @param task
	 * @param pageVo
	 * @return 返回类型 AjaxResult
	 * @date 2016年11月14日
	 */
	@RequestMapping(value = "/showMyRecevieTaskList")
	public @ResponseBody AjaxResult showMyRecevieTaskList(Task task, PaginationVO pageVo) {
		task.setUserId(getMe().getId());// 数据隔离
		return showList(taskService, task, pageVo);
	}

	/**
	 * @Description:我发布的任务列表
	 * @author:dingchuan
	 * @param task
	 * @param pageVo
	 * @return 返回类型 AjaxResult
	 * @date 2016年11月14日
	 */
	@RequestMapping(value = "/showMyPublishTaskList")
	public @ResponseBody AjaxResult showMyPublishTaskList(Task task, PaginationVO pageVo) {
		task.setCreateUserId(getMe().getId());// 数据隔离
		return showList(taskService, task, pageVo);
	}

	/**
	 * 列表显示
	 */
	@RequestMapping(value = "/showList")
	public @ResponseBody AjaxResult showList(Task task, PaginationVO pageVo) {
		return showList(taskService, task, pageVo);
	}

	/**
	 * 新增或者修改页面
	 */
	@RemoveRequestToken
	@RequestMapping(value = "/addOrModify")
	public @ResponseBody AjaxResult addOrModify(Task task) throws Exception {
		int result = 0;
		List<Task> taskList = new ArrayList<Task>();
		String strUserId = task.getStrUserId();// 指派者字符串
		String[] userIdArry = null;
		if (strUserId != null && strUserId != "") {
			userIdArry = strUserId.split(",");
		}
		if (task.getId() != null) {
			result = taskService.modifyOrAdd(task);
			if (result > 0) {
				return new AjaxResult(AjaxResult.STATUS_OK, null, "任务修改成功");
			} else {
				return new AjaxResult(AjaxResult.STATUS_ERR, null, "任务修改失败");
			}
		} else {
			for (int i = 0; i < userIdArry.length; i++) {
				Task addTask = new Task();
				addTask = (Task) task.clone();
				addTask.setUserId(Long.parseLong(userIdArry[i]));
				addTask.setCreateUserId(getMe().getId());
				addTask.setStatus(Dictionary.TASK_STATUS_NO_START);
				addTask.setOvertime(0L);
				addTask.setIsdel(Dictionary.TASK_NO_DEL);
				taskList.add(addTask);
			}
			// 插入数据
			// result = taskService.adds(taskList);
			List<Long> taskIds = taskService.addsAndReturnId(taskList);// 新增task的主键集合
			result = taskIds.size();
			if (result > 0) {
				// 发送OA消息
				SendOaMsgsThread send = new SendOaMsgsThread(taskService, taskIds, Dictionary.BG_COLOR_NO_START,
						Dictionary.TITLE_NO_START, false, null);
				new Thread(send).start();
				// 实时刷新用户信息
				Users users = usersService.findById(getMe().getId());
				WebUtil.getSession().setAttribute("user", users);
				Map<Object, Object> map = new HashMap<Object, Object>();
				map.put("tempUser", users);
				AjaxResult mapResult = new AjaxResult(AjaxResult.STATUS_OK, null, "任务添加成功", Arrays.asList(taskList), 0);
				mapResult.setMapInfo(map);
				return mapResult;
			} else {
				return new AjaxResult(AjaxResult.STATUS_ERR, null, "任务添加失败");
			}

		}
	}

	/**
	 * 进入修改界面
	 */
	@SaveRequestToken
	@RequestMapping(value = "/editForm")
	public String editForm(Long id) {
		Task task;
		if (id != null) {
			task = taskService.findById(id);
			WebUtil.getRequest().setAttribute("obj", task);
			WebUtil.getRequest().setAttribute("copy", false);
		}
		return "admin/task-form";
	}

	/**
	 * 进入复制界面
	 */
	@SaveRequestToken
	@RequestMapping(value = "/copyForm")
	public String copyForm(Long id) {
		Task task;
		if (id != null) {
			task = taskService.findById(id);
			WebUtil.getRequest().setAttribute("obj", task);
			WebUtil.getRequest().setAttribute("copy", true);
		}
		return "admin/task-form";
	}

	/**
	 * @Description:添加评论页面
	 * @author:dingchuan
	 * @param id
	 * @return 返回类型 String
	 * @date 2016年11月15日
	 */
	@SaveRequestToken
	@RequestMapping(value = "/addAssess")
	public String addAssess(Long id) {
		Task task = taskService.findById(id);
		WebUtil.getRequest().setAttribute("obj", task);
		return "admin/task-assess-form";
	}

	/**
	 * @Description:修改评论
	 * @author:dingchuan
	 * @param task
	 * @return 返回类型 AjaxResult
	 * @date 2016年11月22日
	 */
	@RemoveRequestToken
	@RequestMapping(value = "/modifyAssess")
	public @ResponseBody AjaxResult modifyAssess(Task task) {
		Task modifyTask = taskService.findById(task.getId());
		if (modifyTask != null) {
			modifyTask.setAssess(task.getAssess());
			int result = taskService.modify(modifyTask);
			if (result > 0) {
				SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_FORMAT_DD);
				// 创建oa消息
				Map<String, String> oaMap1 = new HashMap<String, String>();
				oaMap1.put("key", "任务状态");
				oaMap1.put("value", Dictionary.TITLE_ASSESS);
				Map<String, String> oaMap2 = new HashMap<String, String>();
				oaMap2.put("key", "被评价人");
				oaMap2.put("value", modifyTask.getAssignName());
				Map<String, String> oaMap3 = new HashMap<String, String>();
				oaMap3.put("key", "评价人");
				oaMap3.put("value", modifyTask.getCreateName());
				Map<String, String> oaMap4 = new HashMap<String, String>();
				oaMap4.put("key", "评价时间");
				oaMap4.put("value", sdf.format(new Date()));
				Map<String, String> oaMap5 = new HashMap<String, String>();
				oaMap5.put("key", "评价内容");
				oaMap5.put("value", modifyTask.getAssess());
				List<Map<String, String>> oaList = new ArrayList<Map<String, String>>();
				oaList.add(oaMap1);
				oaList.add(oaMap2);
				oaList.add(oaMap3);
				oaList.add(oaMap4);
				oaList.add(oaMap5);
				// 发送OA消息
				SendOaMsgsThread send = new SendOaMsgsThread(taskService, Arrays.asList(modifyTask.getId()),
						Dictionary.BG_COLOR_ASSESS, Dictionary.TITLE_ASSESS, false, oaList);
				new Thread(send).start();
				return new AjaxResult(AjaxResult.STATUS_OK, null, "评价成功");
			}
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, null, "评价失败");
	}

	/**
	 * 删除
	 */
	@RequestMapping(value = "/del")
	public @ResponseBody AjaxResult del(String keys) {
		return remove(taskService, keys);
	}

	/**
	 * 激活任务
	 */
	@RequestMapping(value = "/changeTaskActivate")
	public @ResponseBody AjaxResult changeTaskActivate(Long id) {

		Task modifyTask = taskService.findById(id);
		modifyTask.setStatus(Dictionary.TASK_STATUS_YES_START);
		taskService.modify(modifyTask);
		// 发送OA消息
		SendOaMsgsThread send = new SendOaMsgsThread(taskService, Arrays.asList(id), Dictionary.BG_COLOR_NO_START,
				Dictionary.TITLE_NO_START, false, null);
		new Thread(send).start();
		return new AjaxResult(AjaxResult.STATUS_OK, null, "任务已激活");
	}

	/**
	 * @Description:显示所有的任务类型
	 * @author:dingchuan
	 * @return 返回类型 AjaxResult
	 * @date 2016年11月13日
	 */
	@RequestMapping(value = "/showALLTaskType")
	public @ResponseBody AjaxResult showALLTaskType() {
		DataDictionary dataDictionary = new DataDictionary();
		dataDictionary.setType(Dictionary.TASK_TYPE);
		List<DataDictionary> taskLevelList = dataDictionaryService.findByModel(dataDictionary);
		return new AjaxResult(AjaxResult.STATUS_OK, "", "查询成功", taskLevelList, taskLevelList.size());
	}

	/**
	 * @Description:显示所有的任务等级
	 * @author:dingchuan
	 * @return 返回类型 AjaxResult
	 * @date 2016年11月13日
	 */
	@RequestMapping(value = "/showALLTaskLevel")
	public @ResponseBody AjaxResult showALLTaskLevel() {
		DataDictionary dataDictionary = new DataDictionary();
		dataDictionary.setType(Dictionary.TASK_LEVEL);
		List<DataDictionary> taskTypeList = dataDictionaryService.findByModel(dataDictionary);
		return new AjaxResult(AjaxResult.STATUS_OK, "", "查询成功", taskTypeList, taskTypeList.size());
	}

	/**
	 * @Description:改变任务状态为已开始
	 * @author:dingchuan
	 * @return 返回类型 AjaxResult
	 * @date 2016年11月13日
	 */
	@RequestMapping(value = "/changeTaskStart")
	public @ResponseBody AjaxResult changeTaskStart(Task task) {
		Task checkTask = taskService.findById(task.getId());
		String status = checkTask.getStatus();
		if (Dictionary.TASK_STATUS_NO_START.equals(status)) {
			checkTask.setStatus(Dictionary.TASK_STATUS_YES_START);// 已开始
			int result = taskService.modify(checkTask);
			if (result > 0) {
				// 发送oa消息
				List<Long> taskIds = new ArrayList<>();
				taskIds.add(task.getId());
				SendOaMsgsThread send = new SendOaMsgsThread(taskService, taskIds, Dictionary.BG_COLOR_START,
						Dictionary.TITLE_START, true, null);
				new Thread(send).start();
				return new AjaxResult(AjaxResult.STATUS_OK, null, "任务修改成功");
			} else {
				return new AjaxResult(AjaxResult.STATUS_ERR, null, "任务修改失败");
			}
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, "", "状态不是未开始不能修改！", null, null);
	}

	/**
	 * @Description:改变任务状态为已完成
	 * @author:dingchuan
	 * @return 返回类型 AjaxResult
	 * @date 2016年11月13日
	 */
	@RequestMapping(value = "/changeTaskFinish")
	public @ResponseBody AjaxResult changeTaskFinish(Task task) {
		Task finishTask = taskService.finishTask(task);
		if (finishTask != null) {
			// 发送oa消息
			List<Long> taskIds = new ArrayList<>();
			taskIds.add(task.getId());
			SendOaMsgsThread send = new SendOaMsgsThread(taskService, taskIds, Dictionary.BG_COLOR_FINISHED,
					Dictionary.TITLE_FINISHED, true, null);
			new Thread(send).start();
			// 返回用户
			Users users = usersService.findById(getMe().getId());
			WebUtil.getSession().setAttribute("user", users);
			// 返回图标
			ExperienceLevel exLevel = new ExperienceLevel();
			exLevel.setLevelName(getMe().getGrade());
			List<ExperienceLevel> exLevelList = exLevelService.findByModel(exLevel);
			Map<Object, Object> map = new HashMap<Object, Object>();
			map.put("tempUser", users);
			map.put("gradeImg", exLevelList.get(0));
			AjaxResult mapResult = new AjaxResult(AjaxResult.STATUS_OK, null, "操作成功！", Arrays.asList(finishTask), 0);
			mapResult.setMapInfo(map);
			return mapResult;
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, null, "操作失败！");
	}

	/**
	 * @Description:改变任务状态为已取消
	 * @author:dingchuan
	 * @return 返回类型 AjaxResult
	 * @date 2016年11月13日
	 */
	@RequestMapping(value = "/changeTaskCancel")
	public @ResponseBody AjaxResult changeTaskCancel(Task task) {
		Task checkTask = taskService.cancelTask(task);
		if (checkTask != null) {
			// 发送OA消息
			Long userId = getMe().getId();// 当前登录者的id
			List<Long> taskIds = new ArrayList<>();
			taskIds.add(task.getId());
			SendOaMsgsThread send = null;
			if (userId == checkTask.getUserId()) {
				send = new SendOaMsgsThread(taskService, taskIds, Dictionary.BG_COLOR_CANCLE, Dictionary.TITLE_CANCLE,
						true, null);
			} else {
				send = new SendOaMsgsThread(taskService, taskIds, Dictionary.BG_COLOR_CANCLE, Dictionary.TITLE_CANCLE,
						false, null);
			}
			new Thread(send).start();
			// 退回用户金币
			if (!Dictionary.USER_ROLE_ZJL.equals(getMe().getRole().getName())) {
				Users user = getMe();
				int userGoldNum = (user.getAge() != null && user.getAge() > 0) ? user.getAge() : 0;
				int taskGoldNum = (checkTask.getGoldNum() != null && checkTask.getGoldNum() > 0)
						? checkTask.getGoldNum() : 0;
				user.setAge(userGoldNum + taskGoldNum);
				usersService.modify(user);
			}
			return new AjaxResult(AjaxResult.STATUS_OK, "", "任务取消成功!");
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, "", "任务取消失败!");
	}

	/**
	 * @Description:删除任务
	 * @author:chenxianzi
	 * @return 返回类型 AjaxResult
	 * @date 2016年12月16日
	 */
	@RequestMapping(value = "/delTask")
	public @ResponseBody AjaxResult delTask(Task task) {
		int i = taskService.delTask(task);
		if (i > 0) {
			return new AjaxResult(AjaxResult.STATUS_OK, "", "任务删除成功!");
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, "", "任务删除失败!");
	}

	/**
	 * @Description:关注任务
	 * @author:dingchuan
	 * @return 返回类型 AjaxResult
	 * @date 2016年11月13日
	 */
	@RequestMapping(value = "/concernTask")
	public @ResponseBody AjaxResult concernTask(Task task) {
		Task concernTask = taskService.findById(task.getId());
		if (concernTask != null) {
			String concernIds = concernTask.getConcernId();// 关注人ids
			if (concernIds == null || "".equals(concernIds)) {
				concernIds += getMe().getId();
			} else {
				concernIds += "," + getMe().getId();
			}
			concernTask.setConcernId(concernIds);
			int result = taskService.modify(concernTask);
			if (result > 0) {
				return new AjaxResult(AjaxResult.STATUS_OK, null, "关注成功");
			}
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "关注失败！");
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, null, "关注失败！");
	}

	@RequestMapping(value = "/lookForm")
	public String lookForm(Long id) {
		Task task = taskService.findById(id);
		WebUtil.getRequest().setAttribute("obj", task);
		return "admin/task-look-form";
	}

	/**
	 * @Description:查询公司全体员工
	 * @author:dingchuan
	 * @return 返回类型 AjaxResult
	 * @date 2016年11月15日
	 */
	@RequestMapping(value = "/queryAllUser")
	public @ResponseBody AjaxResult queryAllUser() {
		Users user = new Users();
		user.setUserType(Dictionary.USER_TYPE_EMPLOYEE);
		user.setIsDeleted("N");
		List<Users> userList = usersService.findByModel(user);
		if (userList != null && userList.size() > 0) {
			return new AjaxResult(AjaxResult.STATUS_OK, null, "查询成功", userList, userList.size());
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, null, "查询失败");
	}

	/**
	 * @Description:查询所有的项目开发人员
	 * @author:dingchuan
	 * @return 返回类型 AjaxResult
	 * @date 2016年11月15日
	 */
	@RequestMapping(value = "/queryAllProjUser")
	public @ResponseBody AjaxResult queryAllProjUser(ProjUser projUser) {
		List<ProjUser> projUserList = projUserService.findByModel(projUser);
		if (projUserList != null && projUserList.size() > 0) {
			return new AjaxResult(AjaxResult.STATUS_OK, null, "查询成功", projUserList, projUserList.size());
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, null, "查询失败");
	}

	/**
	 * @Description:查询所有的项目
	 * @author:dingchuan
	 * @return 返回类型 AjaxResult
	 * @date 2016年11月27日
	 */
	@RequestMapping(value = "/queryAllProject")
	public @ResponseBody AjaxResult queryAllProject() {
		List<Project> projectList = projectService.findByModel(null);
		if (projectList != null && projectList.size() > 0) {
			return new AjaxResult(AjaxResult.STATUS_OK, null, "查询成功", projectList, projectList.size());
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, null, "查询失败");
	}

	/**
	 * 查询每个人的任务量
	 * 
	 * @return
	 */
	@RequestMapping(value = "/findUserTask")
	public @ResponseBody AjaxResult findUserTask() {
		List<Map<Object, Object>> rows = utilDao.selectUserTask();
		AjaxResult result = new AjaxResult(AjaxResult.STATUS_OK, null, "查询成功");
		result.setRows(rows);
		return result;
	}

	/**
	 * 甘特图显示用户任务情况
	 * 
	 * @return
	 */
	@RequestMapping(value = "/findUserTaskForChart")
	public @ResponseBody AjaxResult findUserTaskForChart(int year, int month) {

		// 获取本月天数
		Calendar calendar = Calendar.getInstance();
		calendar.set(year, month - 1, 1, 0, 0, 0);
		int maxDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
		Date beginTime = calendar.getTime();
		calendar.set(year, month - 1, maxDays, 23, 59, 59);
		Date endTime = calendar.getTime();

		// 获取公司人员，以及人员的任务
		Users userQuery = new Users();
		userQuery.setIsDeleted(Dictionary.DELETED_N);
		userQuery.setCompanyId(getMe().getCompanyId());
		userQuery.setUserType(Dictionary.USER_TYPE_EMPLOYEE);
		List<Users> users = usersService.findByModel(userQuery);
		for (Users user : users) {
			user.setTasks(taskService.findTaskByMonth(user.getId(), beginTime, endTime));
		}
		AjaxResult result = new AjaxResult(AjaxResult.STATUS_OK, null, "查询成功");
		result.setRows(users);
		result.putInMap("maxDays", maxDays);

		return result;
	}
 

}